//录面板
var gridPanel;
//表单窗口
var contentPanel;
//单面板
var formPanel;
//页面布局管理器
var viewport = null;
//服务处理标志
var processFlag = false;

Date.prototype.toString=function(){ 
  return this.format("Ymd"); 
};

var configFormWindow;
var configFormPanel;
var uploadFormWindow;
var uploadFormPanel;
var envType = '';

var recordDef = Ext.data.Record.create([{name:'code'},{name:'name'}]);
var projectDataStore = new Ext.data.Store({
	proxy:new Ext.data.HttpProxy({url:'/getApplications'}),
	reader:new Ext.data.JsonReader({id:'code',root:'comboBox'},recordDef),
	remoteStore:true
});

//格式化日期  
function formatDate(value) {  
    if (Ext.isEmpty(value)) {//判断是否是日期类型的数据  
        return '';  
    } else {  
        if (Ext.isDate(value)){  
        	alert("1  "+value+"  "+Ext.util.Format.date(value, 'Ymd'));
            return ""+Ext.util.Format.date(value, 'Ymd');// 用于时间控件返回值  
        }
        else  {  
        	alert("2  "+value+"  "+Ext.util.Format.date(new Date(value), 'Ymd'));
            return Ext.util.Format.date(new Date(value), 'Ymd');// 转换为Date类型  
        }
    }  
} 

//创建活动面板
function createGridPanel(){
	//检查对象是否已经创建
	if( gridPanel!=null ) return;
	//设置数据源
	var ds = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({url:systemContext + '/configlog/page'}),
		reader: new Ext.data.JsonReader({
			root: 'records',
			totalProperty: 'total',
			id: 'configId'
			},
			['logId','appId','appName','envType','configId','createTime','isCast','newJson','operateType','originJson','updateTime']
		)
	});

	//列选择模式
	var sm = new Ext.grid.CheckboxSelectionModel();
	//列表名
	var colModel = new Ext.grid.ColumnModel([        
        new Ext.grid.RowNumberer({header:"序号",width:30}),
        sm,
        {header:"日志ID",dataIndex:"logId",width:50},
        {header:"配置键ID",dataIndex:"configId",width:80},
        {header:"环境",dataIndex:"envType",width:80,renderer:function(value){
        	if( value=='dev'){
        		return '开发环境';
        	}else if( value=='test'){
        		return '测试环境';
        	}else if( value=='stat'){
        		return '预发布环境';
        	}else if( value=='prod'){
        		return '预发布环境';
        	}else{
        		return '其他';
        	}
        }},
        {header:"所属项目",dataIndex:"appName",width:140},
        {header:"修改后内容",dataIndex:"newJson",width:280},
        {header:"修改前内容",dataIndex:"originJson",width:280},
        {header:"操作类型",dataIndex:"operateType",width:70,renderer:function(value){
        	if( value=='0'){
        		return '新增';
        	}else if( value=='1'){
        		return '修改';
        	}else {
        		return '删除';
        	}
        }},
        {header:"是否为公共配置",dataIndex:"isPublic",width:70,renderer:function(value){
        	if( value=='1'){
        		return '公共配置';
        	}else {
        		return '否';
        	}
        }},
        {header:"是否已广播",dataIndex:"isCast",width:70,renderer:function(value){
        	if( value=='1'){
        		return '已广播';
        	}else {
        		return '未广播';
        	}
        }},
        {header:"创建时间",dataIndex:"createTime",width:100,editor: new Ext.form.TextField({allowBlank: false})}
    ]);
	colModel.defaultSortable = true;
	//创建grid面板
	gridPanel = new Ext.grid.EditorGridPanel({
			border:false,
			buttonAlign :'left',
			loadMask: true,
			store: ds,
			autoExpandColumn:6,
			height:'100%',
			autoWidth:false,
			cm: colModel,
			sm: sm,
			autoScroll: true,
			tbar: [
				'环境：',{xtype:'tbseparator'},new Ext.form.ComboBox({
				    store: new Ext.data.SimpleStore({
					    fields: ['returnValue', 'displayValue'],
					    data : [['','所有'],['dev','开发环境'], ['test','测试环境'], ['stat','预发布环境'], ['test','生产环境']]
					}),
				    displayField:'displayValue',
				    valueField:'returnValue',
				    typeAhead: true,
				    mode: 'local',
				    editable:false,
				    hiddenName:'envType',
					width:100,
				    triggerAction: 'all',
				    emptyText:'全部',
				    selectOnFocus:true,
				    fieldLabel : '操作类型',
					anchor:'80%',
					name : 'envType',
					listeners: {
			            select: function(combo, record, index) {
			            	envType = combo.getValue();
			            	console.log(envType);
			            }
			        }
				}),
				'日志ID：',{xtype:'textfield',width:80,id:'logId',name:'logId'},{xtype:'tbseparator'},
				'应用：',{
					xtype : 'combo',
					store : projectDataStore,
					displayField : 'name',
					valueField : 'code',
					typeAhead : true,
					mode : 'remote',
					triggerAction : 'all',
					width: 240,
					emptyText : '请选择应用...',
					selectOnFocus : true,
					resizable : true,
					hiddenName : 'appId',
					listeners:{
						focus:function(combo,record,index){
							projectDataStore.proxy = new Ext.data.HttpProxy( {  
                                url : '/getApplications?envType='  + envType  
                            });  
							projectDataStore.reload();
			            }
			        }
				},{xtype:'tbseparator'},
				'操作类型：',{xtype:'tbseparator'},new Ext.form.ComboBox({
				    store: new Ext.data.SimpleStore({
					    fields: ['returnValue', 'displayValue'],
					    data : [['','全部'],['0','新增'],['1','修改'],['2','删除']]
					}),
				    displayField:'displayValue',
				    valueField:'returnValue',
				    typeAhead: true,
				    mode: 'local',
				    editable:false,
				    hiddenName:'operateType',
					width:100,
				    triggerAction: 'all',
				    emptyText:'全部',
				    selectOnFocus:true,
				    fieldLabel : '操作类型',
					anchor:'80%',
					name : 'operateType',
				}),{xtype:'tbseparator'},'是否已广播：',{xtype:'tbseparator'},new Ext.form.ComboBox({
				    store: new Ext.data.SimpleStore({
					    fields: ['returnValue', 'displayValue'],
					    data : [['','全部'],['1','已广播'],['0','未广播']]
					}),
				    displayField:'displayValue',
				    valueField:'returnValue',
				    typeAhead: true,
				    mode: 'local',
				    editable:false,
				    hiddenName:'isCast',
					width:100,
				    triggerAction: 'all',
				    emptyText:'全部',
				    selectOnFocus:true,
				    fieldLabel : '操作类型',
					anchor:'80%',
					name : 'isCast',
				}),{xtype:'tbseparator'},
				{text:'搜索',iconCls:'icon-search',handler:function(){
					ds.load({
				    	params:{start:0, limit:50}
				    });
				}},{xtype:'tbseparator'},
				{text:'广播更改',iconCls:'rec_publish',handler:function(){
					Ext.MessageBox.confirm('确认对话框', '确认广播通知所有服务器更新配置？', function(btn){
	    				if(btn=='yes'){
	    					processFlag = true;
	    					showWaitingBar();
	    					Ext.Ajax.request({// 排列顺序
								url : '/notifyRefresh',
								method : 'GET',
								success : function(response,action) {
									processFlag = false;
									Ext.MessageBox.hide();
									var responseArray = Ext.util.JSON.decode(response.responseText);
									if( responseArray.respMsg!=null ){
										Ext.MessageBox.alert('提示框',responseArray.respMsg);
									}
									ds.load({
								    	params:{start:0, limit:50}
								    });
								},
								failure : processFailure
							});
	    				}
					});
				}}							
				],
			bbar : new Ext.PagingToolbar({
				pageSize: 25,
				store: ds,
				displayInfo: true,
				displayMsg: '第{0} 到 {1} 页数据 共{2}条',
				emptyMsg: '未查询到资源'
			})
	});
	//加载数据
	ds.load({params:{start:0, limit:25}});
	ds.on('beforeload',function(){ 
	 		Ext.apply(this.baseParams,{envType:Ext.get('envType').dom.value,logId:Ext.get('logId').dom.value,
	 			appId:Ext.get('appId').dom.value,
	 			operateType:Ext.get('operateType').dom.value,isCast:Ext.get('isCast').dom.value}
	  	);
	});
}

// 创建活动内容面板
function createContentPanel(){
	this.contentPanel = new Ext.Panel({
		split : true,
		bodyStyle : "width:100%",
		region : 'center',
		layout:'fit',
		margins : '0 0 0 0',
		forceFit : true,
		stripeRows : true,
	    enableTextSelection : true 
	});
}

//页面初始化
function init(){
	// 创建对象
	this.createContentPanel();
	this.createGridPanel();
	this.contentPanel.add(this.gridPanel);
	//carete add config window and form
	this.createConfigFormWindow();
	this.createConfigFormPanel();
	this.configFormWindow.add(this.configFormPanel);
	
	//布局管理器
	this.viewport = new Ext.Viewport({
			layout:'border',
			border:true,
			items:[this.contentPanel]
	});
	this.viewport.render();
}

//删除选中的
function delRecords(records){
	var configIds = new Array();
	var index = 0;
	for( var i=0;i<records.length;i++ ){
		configIds.push(records[i].get('basicId'));
	}
	if( configIds.length==0 ){
		processFlag = false;
		return;
	}
	processFlag = true;
	this.showWaitingBar();
	Ext.Ajax.request({// 排列顺序
		url : systemContext + '/deleteProjects',
		params : {
			basicId : configIds
		},
		method : 'POST',
		success : function(response,action) {
			processFlag = false;
			var responseArray = Ext.util.JSON.decode(response.responseText);
			Ext.MessageBox.alert('提示框',responseArray.respMsg);
			gridPanel.getStore().load({
				params:{start:0, limit:50}
			});
		},
		failure : processFailure
	});
}

//批量保存数据
function batchSaveRecord(){
	var vRecords = gridPanel.getStore().getModifiedRecords(); //得到修改的数据（记录对象）
	var vCount = vRecords.length; //得到记录长度
	if (vCount > 0) {
        //begin 将记录对象转换为字符串（json格式的字符串）
        var vDatas = '[';
        for (var i = 0; i < vCount; i++) {
            vDatas += Ext.util.JSON.encode(vRecords[i].data) + ',';
        }
        vDatas = vDatas.substr(0, vDatas.length - 1) + ']';
        processFlag = true;
        this.showWaitingBar();
        Ext.Ajax.request({// 排列顺序
    		url : '/batchSaveProjects',
    		method : 'POST',
    		params: {datas: vDatas},
    		success : function(response,action) {
    			processFlag = false;
    			var responseArray = Ext.util.JSON.decode(response.responseText);
    			if( responseArray.respMsg!=null ){
    				Ext.MessageBox.alert('提示框',responseArray.respMsg);
    			}
    			if( responseArray.success){
    				gridPanel.getStore().commitChanges();
    				gridPanel.getStore().load({
    					params:{start:0, limit:50}
    				});
    			}
    		},
    		failure : processFailure
    	});
    }
}

//创建用户窗口面板
function createConfigFormWindow(){
	configFormWindow = new Ext.Window({
		title : '添加应用信息',
		id : 'configFormWindow',
        layout:'fit',
        width:380,
        height:250,
        closeAction:'hide',
        plain: true,
        modal:true,
        collapsible: false,
        maximizable:false,
        draggable: true,
        closable: false,
        resizable:false,
        animateTarget:document.body
	});
}
//创建用户表单面板
function createConfigFormPanel(){
	configFormPanel = new Ext.FormPanel({
		labelWidth : 90,
		labelAlign:'right',
		id:'configFormPanel',
		frame : true,
		border:false,
		bodyStyle : 'padding:0px 0px 0',
		defaultType : 'textfield',
		items : [{
        	fieldLabel: '环境代码',
		    name: 'environment',   
		    maxLength:'80',
			minLength:'3',
			width: 200,
			allowBlank: false,
            blankText: '环境代码不能为空',
		    minLengthText: '环境代码长度必须在6到16位之间',
		    maxLengthText: '环境代码长度必须在6到16位之间'
   	 	},{
        	fieldLabel: '环境名称',
		    name: 'environmentDesc',   
		    maxLength:'80',
			minLength:'3',
			width: 200,
			allowBlank: false,
            blankText: '环境名称不能为空',
		    minLengthText: '环境名称长度必须在6到16位之间',
		    maxLengthText: '环境名称长度必须在6到16位之间'
   	 	},{
        	fieldLabel: '项目代码',
		    name: 'projectName',   
		    maxLength:'80',
			minLength:'3',
			width: 200,
			allowBlank: false,
            blankText: '项目代码不能为空',
		    minLengthText: '项目代码长度必须在6到16位之间',
		    maxLengthText: '项目代码长度必须在6到16位之间'
   	 	},{
        	fieldLabel: '项目名称',
		    name: 'projectNameDesc',   
		    maxLength:'80',
			minLength:'3',
			width: 200,
			allowBlank: false,
            blankText: '项目名称不能为空',
		    minLengthText: '名称代码长度必须在6到16位之间',
		    maxLengthText: '名称代码长度必须在6到16位之间'
   	 	},{
			allowBlank: false,  
		    name: 'version', 
		    width: 200,
		    fieldLabel: '版本',
            blankText: '版本值不能为空'
   	 	},{
   	 		width: 200,
			allowBlank: false,  
		    name: 'memo', 
		    fieldLabel: '备注描述'
   	 	}],
		buttons : [{
			text : '保存',
			handler:function(){
				var configForm = configFormPanel.getForm();
				if( configForm.isValid() ){
					saveAddProject(configForm);
				}
			}
		}, {
			text : '取消',
			handler:function(){
				configFormWindow.hide();
			}
		}]
	});
}
function saveAddProject(form){
	form.submit({
		url : '/saveAddProject',
		method : 'POST',
		success : function(from, action) {
			if( action.success ){
				configFormWindow.hide();
				configFormPanel.getForm().reset();
			}
			Ext.MessageBox.alert('提示框',action.result.respMsg);
			gridPanel.getStore().load({
				params:{start:0, limit:50}
			});
			},
		failure : processFailure,
		waitMsg : '正在保存数据，稍后...',
		waitTitle:'提示'
	});
}
